'use strict';

module.exports = core;

const path = require('path');
const minimist = require('minimist');
const pathExists = require('path-exists').sync;
const userHome = require('user-home');
const dotenv = require('dotenv');
const rootCheck = require('root-check');
const colors = require('colors/safe');
const pkg = require('../package.json');
const logger = require('@atri-cli/log');
const semver = require('semver');
const constant = require('./constant');

async function core() {
    // try {
    checkPkgVersion();
    checkNodeVersion();
    checkRoot();
    checkUserHome();
    checkInputArgs();
    await checkGlobalUpdate();
    // checkEnv();
    // } catch (e) {
    //     logger.error(e.message);
    // }

}

// function checkEnv() {
//     const dotenvPath = path.resolve(userHome, '.env');
//     if (pathExists(dotenvPath)) {
//         const config = dotenv.config({
//             path: dotenvPath
//         });
//     }
//     createDefaultConfig();

//     console.log(config);
// }

// function createDefaultConfig() {
//     const cliConfig = {
//         home: userHome
//     }
//     if (process.env.CLI_HOME) {
//         cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME);
//     } else {
//         cliConfig['cliHome'] = path.join(userHome, process.env.DEFAULT_CLI_HOME);

//     }
//     process.env.CLI_HOME_PATH = cliConfig.cliHome;
//     return cliConfig;
// }
async function checkGlobalUpdate() {
    const currentVersion = pkg.version;
    const pkgName = pkg.name;
    const npmInfo = await getNpmInfo(pkgName);
    console.log(npmInfo);
}


function getNpmInfo(npmName) {
    if (!npmName) return null;
    const registry = 'https://registry.npm.taobao.org/';
    const npmInfoUrl = registry + npmName;
    return axios.get(npmInfoUrl).then((res) => {
        if (res.status === 200) {
            return res.data;
        }
        return null;
    }).catch((err) => {
        return Promise.reject(err);
    });
}


function checkInputArgs() {
    const args = minimist(process.argv.slice(2));
    checkArgs(args);
}

function checkArgs(args) {
    if (args.debug) {
        process.env.LOG_LEVEL = 'verbose';
    } else {
        process.env.LOG_LEVEL = 'info';

    }
    logger.LOG_LEVEL = process.env.LOG_LEVEL;
    console.log(process.env.LOG_LEVEL);
}


function checkRoot() {
    rootCheck();
}

function checkNodeVersion() {
    const currentVersion = process.version;
    const lowestVersion = constant.LOWEST_NODE_VERSION;
    if (!semver.gte(currentVersion, lowestVersion)) {
        const msg = `你的Node版本过低
        当前版本: ${currentVersion}
        最低版本: ${lowestVersion}`;
        throw new Error(colors.red(msg))
    }
}

function checkPkgVersion() {
    logger.notice('cli', pkg.version);
}

function checkUserHome() {
    if (!userHome || !pathExists(userHome)) {
        throw new Error(colors.red('主目录不存在'));
    }
}

